package com.ruoyi.cms.controller;

import com.ruoyi.cms.utils.CmsUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import java.util.List;

import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cms.domain.CmsSite;
import com.ruoyi.cms.domain.dto.CmsSiteDTO;
import com.ruoyi.cms.service.ICmsSiteService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.HTExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 站点信息Controller
 * 
 * @author ruoyi
 * @date 2021-07-28
 */
@Api(tags = "站点信息")
@Controller
@RequestMapping("/cms/site")
public class CmsSiteController extends BaseController {

    private final String prefix = "cms/site";

    @Autowired
    private ICmsSiteService cmsSiteService;

    @Autowired
    private ISysUserService sysUserService;

    @RequiresPermissions("cms:site:view")
    @GetMapping()
    public String site() {
        return prefix + "/site";
    }

    /**
     * 查询站点信息列表
     */
    @ApiOperation("查询站点信息列表")
    @RequiresPermissions("cms:site:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo<CmsSite> list(CmsSiteDTO cmsSite) {
        startPage();
        List<CmsSite> list = cmsSiteService.selectCmsSiteList(cmsSite.as());
        return getDataTable(list);
    }

    /**
     * 导出站点信息列表
     */
    @ApiOperation(value="导出站点信息列表", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @RequiresPermissions("cms:site:export")
    @Log(title = "站点信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult<?> export(CmsSiteDTO cmsSite) {
        List<CmsSite> list = cmsSiteService.selectCmsSiteList(cmsSite.as());
        return HTExcelUtil.exportExcel(CmsSite.class, list, queryVisibleFields());
    }

    /**
     * 新增站点信息
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存站点信息
     */
    @ApiOperation("新增保存站点信息")
    @RequiresPermissions("cms:site:add")
    @Log(title = "站点信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult<?> addSave(@Validated CmsSiteDTO cmsSite) {
        cmsSite.setSiteId(null);
        cmsSite.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(cmsSiteService.insertCmsSite(cmsSite.as()));
    }

    /**
     * 修改站点信息
     */
    @GetMapping("/edit/{siteId}")
    public String edit(@PathVariable("siteId") Long siteId, ModelMap mmap)
    {
        CmsSite cmsSite = qrySite(siteId);
        mmap.put("cmsSite", cmsSite);
        return prefix + "/edit";
    }

    /**
     * 修改保存站点信息
     */
    @ApiOperation("修改保存站点信息")
    @RequiresPermissions("cms:site:edit")
    @Log(title = "站点信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult<?> editSave(@Validated CmsSiteDTO cmsSite) {
        if (null == cmsSite.getSiteId()) {
            return AjaxResult.error("ID不能为空");
        }
        qrySite(cmsSite.getSiteId());
        cmsSite.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(cmsSiteService.updateCmsSite(cmsSite.as()));
    }

    /**
     * 删除站点信息
     */
    @ApiOperation("删除站点信息")
    @ApiImplicitParam(name = "ids", value = "站点信息ID.多个ID间以英文逗号隔开", dataType = "String", paramType = "query", required = true)
    @RequiresPermissions("cms:site:remove")
    @Log(title = "站点信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult<?> remove(String ids) {
        return toAjax(cmsSiteService.deleteCmsSiteByIds(ids));
    }

    /**
     * 切换站点
     * @param siteId
     * @return
     */
    @ApiOperation("切换站点")
    @GetMapping("/switch/{siteId}")
    @ResponseBody
    public AjaxResult<String> switchSite(@ApiParam(value = "站点ID", required = true) @PathVariable Long siteId) {
        CmsSite site = cmsSiteService.switchSite(siteId);
        return null != site ? AjaxResult.success() : AjaxResult.error("切换站点失败");
    }

    /**
     * 当前站点
     * @return
     */
    @ApiOperation("当前站点")
    @GetMapping("/curr")
    @ResponseBody
    public AjaxResult<CmsSite> currSite() {
        CmsSite site = cmsSiteService.currSite();
        return null != site ? AjaxResult.success(site) : AjaxResult.error("请在站点管理中执行切换站点操作");
    }

    @RequiresPermissions("cms:site:user")
    @GetMapping("/user/insite/{siteId}")
    public String toUserInSite(@PathVariable Long siteId, ModelMap mmap) {
        mmap.put("site", qrySite(siteId));
        return prefix + "/userinsite";
    }

    @RequiresPermissions("cms:site:user")
    @GetMapping("/user/notinsite/{siteId}")
    public String toUserNotInSite(@PathVariable Long siteId, ModelMap mmap) {
        mmap.put("site", qrySite(siteId));
        return prefix + "/usernotinsite";
    }

    /**
     * 站点用户
     * @param param
     * @return
     */
    @RequiresPermissions("cms:site:user")
    @ApiOperation("查询站点用户")
    @PostMapping("/user/insite")
    @ResponseBody
    public TableDataInfo<SysUser> userInSite(SysUser param) {
        if (!param.getParams().containsKey("inSiteId")) {
            param.getParams().put("inSiteId", cmsSiteService.currSiteId());
        }
        startPage();
        List<SysUser> list = sysUserService.selectUserList(param);
        list.forEach(u -> u.sm4Dec().desensitized());
        return getDataTable(list);
    }

    /**
     * 非站点用户
     * @param param
     * @return
     */
    @RequiresPermissions("cms:site:user")
    @ApiOperation("查询站点用户")
    @PostMapping("/user/notinsite")
    @ResponseBody
    public TableDataInfo<SysUser> userNotInSite(SysUser param) {
        if (!param.getParams().containsKey("notInSiteId")) {
            param.getParams().put("notInSiteId", cmsSiteService.currSiteId());
        }
        startPage();
        List<SysUser> list = sysUserService.selectUserList(param);
        list.forEach(u -> u.sm4Dec().desensitized());
        return getDataTable(list);
    }

    /**
     * 添加站点用户
     * @param siteId
     * @param userIds
     * @return
     */
    @RequiresPermissions("cms:site:user")
    @Transactional
    @ApiOperation("添加站点用户")
    @PostMapping("/user/add")
    @ResponseBody
    public AjaxResult<String> addSiteUser(@ApiParam(value = "站点ID", required = true) Long siteId,
                                          @ApiParam(value = "用户ID.多个ID间以英文逗号隔开", required = true) String userIds) {
        CmsSite site = qrySite(siteId);
        CmsUtil.checkIds(userIds, "用户ID").forEach(uid -> cmsSiteService.insertCmsSiteuser(siteId, uid));
        return AjaxResult.success();
    }

    /**
     * 删除站点用户
     * @param siteId
     * @param userIds
     * @return
     */
    @RequiresPermissions("cms:site:user")
    @Transactional
    @ApiOperation("删除站点用户")
    @PostMapping("/user/remove")
    @ResponseBody
    public AjaxResult<String> removeSiteUser(@ApiParam(value = "站点ID", required = true) Long siteId,
                                             @ApiParam(value = "用户ID.多个ID间以英文逗号隔开", required = true) String userIds) {
        CmsSite site = qrySite(siteId);
        CmsUtil.checkIds(userIds, "用户ID").forEach(uid -> cmsSiteService.deleteCmsSiteuser(siteId, uid));
        return AjaxResult.success();
    }

    /**
     * 查找站点
     * @param siteId
     * @return
     */
    private CmsSite qrySite(Long siteId) {
        return cmsSiteService.selectCmsSite(siteId, ShiroUtils.getUserId())
                .orElseThrow(() -> new BusinessException("站点不存在或已删除"));
    }
}
